package com.squid.base.common.annotation.time;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

/**
 * 检测方法执行时间
 *
 * @author jh
 * @date 2022/12/6 16:25
 */
@Slf4j
@Component
@Aspect
public class CheckMethodTimeAspect {
    @Pointcut("@annotation(com.squid.base.common.annotation.time.CheckMethodTime)")
    public void myPointcut() {

    }

    @Around("@annotation(checkMethodTime)")
    public Object isAccessMethod(ProceedingJoinPoint joinPoint, CheckMethodTime checkMethodTime) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object obj = joinPoint.proceed(joinPoint.getArgs());
        stopWatch.stop();
        long cost = stopWatch.getTotalTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = StringUtils.hasText(checkMethodTime.methodName()) ?
                checkMethodTime.methodName() : signature.getDeclaringTypeName() + "." + signature.getName();
        log.info("----------- 执行: {} 方法, 用时: {} ms -----------", methodName, cost);
        return obj;
    }
}
